import { GoodsData } from '../../assets/data/data'
import { useCallback, useRef, useState } from 'react'
import {
  OwlWaterfallMethod,
  owlWaterfallRenderItem,
} from '../../component/common/owlWaterfallType'
import OwlWaterfall from '../../component/common/owlWaterfall'
import GoodCard from '../../component/home/goodCard'
export default function RecommondTab() {
  const [list, setList] = useState(
    GoodsData.map(item => Object.assign({}, item)),
  )
  const listRef = useRef<OwlWaterfallMethod>(null)
  const [params, setParams] = useState({
    size: 10,
    current: 1,
    total: 10,
  })

  async function onRefresh() {
    await new Promise(res => {
      const obj = Object.assign({}, params, { current: 1 })
      params.current = 1
      setTimeout(() => {
        const data = GoodsData.map(item => Object.assign({}, item)).sort(
          () => Math.random() - Math.random(),
        )
        setList(data)
        listRef.current?.resetData(data)
        setParams(obj)
        res(0)
      }, 1000)
    })
  }

  const onScrollBottom = useCallback(async () => {
    await new Promise(res => {
      const obj = Object.assign({}, params, { current: ++params.current })
      const crn = (obj.current - 1) * 10
      setTimeout(() => {
        let appendData = GoodsData.map(item =>
          Object.assign({}, item, { id: item.id + crn }),
        )
        appendData = appendData.sort(() => Math.random() - Math.random())
        setList(val => val.concat(appendData))
        listRef.current?.appendData(appendData)
        setParams(obj)
        res(1)
      }, 1000)
    })
  }, [params])

  const renderItem: owlWaterfallRenderItem = (item: any, onLayout) => {
    return (
      <GoodCard source={item.cover} {...item} onLayout={e => onLayout(e)} />
    )
  }
  return (
    <OwlWaterfall
      pagination={params}
      data={list}
      ref={listRef}
      onScrollBottom={onScrollBottom}
      onRefresh={onRefresh}
      renderItem={renderItem}
    />
  )
}
